package com.zebraphp.devtool.httpUtils.NetOkHttp.requestBuilder;

import com.zebraphp.devtool.httpUtils.NetOkHttp.IOkHttp;
import com.zebraphp.devtool.httpUtils.NetOkHttp.responseHandler.BaseHandler;

import java.util.LinkedHashMap;
import java.util.Map;

import okhttp3.Headers;
import okhttp3.Request;


/**
 * 不带 param 的base request body
 */
public abstract class BaseBuilder<T extends BaseBuilder> {
    protected Map<String, String> mHeaders;//请求头

    protected String mUrl;//请求地址
    protected Object mTag;//请求标签

    protected IOkHttp mIOkHttp;

    public BaseBuilder(IOkHttp IOkHttp) {
        mIOkHttp = IOkHttp;
    }

    /* 异步执行 @param responseHandler 自定义回调 */
    public abstract void addTaskQueue(final BaseHandler responseHandler);

    /*设置url地址*/
    public T setUrl(String url) {
        this.mUrl = url;
        return (T) this;//返回当前对象,便于对象链式操作
    }

    /* 设置请求的标签 用于后面通过标签 来取消请求*/
    public T setTag(Object tag) {
        this.mTag = tag;
        return (T) this;
    }

    /* 设置请求头*/
    public T setHeaders(Map<String, String> headers) {
        this.mHeaders = headers;
        return (T) this;
    }

    /* 单个添加请求头*/
    public T addHeader(String key, String val) {
        if (null == this.mHeaders) {
            mHeaders = new LinkedHashMap<>();
        }
        mHeaders.put(key, val);
        return (T) this;
    }

    //把设置好的请求头加入到 builder中去
    protected void appendFinalHeadersToRequest(Request.Builder builder, Map<String, String> headers) {
        Headers.Builder headerBuilder = new Headers.Builder();

        //如果headers是空
        if (headers == null || headers.isEmpty()) return;

        //构建 添加到Builder的请求头中去
        for (String key : headers.keySet()) {
            headerBuilder.add(key, headers.get(key));
        }

        builder.headers(headerBuilder.build());
    }
}
